﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Otonomos.Utils.Serialization
{
    public class JsonSerializer : ISerializer
    {
        private JsonSerializerSettings mSerializerSettings;

        public JsonSerializer()
        {
            mSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
            var contractResolver = new DefaultContractResolver();
            contractResolver.DefaultMembersSearchFlags |= BindingFlags.NonPublic;
            mSerializerSettings.ContractResolver = contractResolver; 
        }

        public void Serialize<T>(T obj, string fileName)
        {
            string serializedObj = JsonConvert.SerializeObject(obj, mSerializerSettings);
            using (var streamWriter = new StreamWriter(fileName))
            {
                streamWriter.Write(serializedObj);
                streamWriter.Close();
            }
        }

        public T Deserialize<T>(string fileName)
        {
            string fileContent = null;
            using (var streamReader = new StreamReader(fileName))
            {
                fileContent = streamReader.ReadToEnd();
                streamReader.Close();
            }

            return JsonConvert.DeserializeObject<T>(fileContent, mSerializerSettings);
        }

        public string DefaultExtension 
        { 
            get { return "json"; } 
        }
    }
}
